package com.yanfan.modbus.frame.abs;


import com.yanfan.modbus.ModbusUtils;
import com.yanfan.modbus.exception.ModbusTransportException;
import io.netty.buffer.ByteBuf;


abstract public class ReadBinaryRequest extends ModbusRequest {
    protected int startOffset;
    protected int numberOfBits;


    public ReadBinaryRequest(int slaveId, int startOffset, int numberOfBits) throws ModbusTransportException {
        super(slaveId);
        this.startOffset = startOffset;
        this.numberOfBits = numberOfBits;
    }

    public ReadBinaryRequest(int slaveId) throws ModbusTransportException {
        super(slaveId);
    }


    @Override
    public void validate() throws ModbusTransportException {
        ModbusUtils.validateOffset(startOffset);
        ModbusUtils.validateNumberOfBits(numberOfBits);
        ModbusUtils.validateEndOffset(startOffset + numberOfBits - 1);
    }


    @Override
    protected void writeRequest(ByteBuf buf) {
        buf.writeShort(startOffset);
        buf.writeShort(numberOfBits);
    }


    @Override
    protected void readRequest(ByteBuf buf) {
        startOffset = buf.readUnsignedShort();
        numberOfBits = buf.readUnsignedShort();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return " startOffset=" + startOffset + ", numberOfBits=" + numberOfBits;
    }
}
